package com.mgfireworks.mgplatform;

import cn.hn.java.summer.mvc.WebContext;
import com.mgfireworks.mgplatform.mgshop.comm.Constants;
import com.mgfireworks.mgplatform.mgshop.main.AccountService;
import com.mgfireworks.mgplatform.mgshop.model.ShopUserInfoVo;
import com.mgfireworks.mgplatform.mgshop.model.ShopUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class ActionInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private AccountService accountService;
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);	
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//为上下文准备response
		WebContext.preperedResponse(response);
		// 设置用户信息
		String userAccount=WebContext.getSessionCookie(Constants.USER_SESSION_KEY,String.class);
		//登录检测
		String root=request.getContextPath();
		String url=request.getRequestURI();
		if(
				userAccount==null &&
				!url.startsWith(root+"/login") &&
				!url.startsWith(root+"/test")&&
				!url.startsWith(root+"/account/weiXinOAuthCallBack")
		){
			WebContext.redirectTo("/login");
		}

		ShopUserVo user=accountService.getShopUser(userAccount);
		ShopUserInfoVo userInfo=accountService.getShopUserInfo(user.getUserId());
		request.setAttribute("user",user);
		request.setAttribute("userInfo",userInfo);
		return super.preHandle(request, response, handler);
	}
}
